package com.wanhai.itm.services;

import com.wanhai.itm.entity.User;
import org.zkoss.json.JSONObject;
import org.zkoss.json.JSONValue;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.WebApps;

/**
 *
 * @author Richard Shih
 */
public class AuthenticationServiceImpl extends AuthenticationService {

    public static final String KEY_USER_INFO = "USER_INFO";
    //service
    private UserInfoService service = UserInfoService.getDefaultService();

    @Override
    public boolean login(String userid, String password) {
        //TODO implement login process here
        String loginUsers = WebApps.getCurrent().getConfiguration().getPreference("login-users", null);
        JSONObject users = (JSONObject) JSONValue.parse(loginUsers);
        JSONObject userObj = (JSONObject) users.get(userid);
        if (userObj != null) {
            if (!String.valueOf(password).equals(userObj.get("password"))) {
                return false;
            }
        } else {
            return false;
        }

        Session session = Executions.getCurrent().getSession();
        User user = service.findUser(userid);
        if (user == null) {
            return false;
        }
        session.setAttribute(KEY_USER_INFO, user);
        return true;
    }

    @Override
    public void logout() {
        Session session = Executions.getCurrent().getSession();

        if (session.hasAttribute(KEY_USER_INFO)) {
            session.removeAttribute(KEY_USER_INFO);
        }
    }

    @Override
    public User getAuthorizedUser() {
        Session session = Executions.getCurrent().getSession();

        if (session.hasAttribute(KEY_USER_INFO)) {
            return (User) session.getAttribute(KEY_USER_INFO);
        }
        return null;
    }
}
